# -*- coding: utf-8 -*-
import os
from ss.file import File
from ss.projectfile import ProjectFile
from ss.versionfile import VersionFile
from ss.dispatch import run

__author__ = 'andrey'

run()

File.database = '~/development/repo/vss_budget/data'

phys_cache = {'$': 'aaaaaaaa'}

class PathNotFoundError(Exception):
    def __init__(self, path):
        self.path = path
    def __str__(self):
        return 'path not found: ' + self.path

def phys(path):
    if not path:
        raise PathNotFoundError('')
    if path in phys_cache:
        return phys_cache[path]
    parent, dir = os.path.split(path)
    phys_parent = phys(parent)
    if not dir:
        return phys_parent
    vf = VersionFile(phys_parent)
    for entry in ProjectFile(vf.filename + vf.info().ext):
        if entry.name.lower() == dir:
            phys_cache[parent + '/' + dir] = entry.phys
            return entry.phys
    raise PathNotFoundError(path)

def ls(project, recursive=False, deleted=False, action=None, subaction=lambda x: None):
    def lsrec(path, phys):
        subaction(path)
        proj = VersionFile(phys)
        subprojs = []
        for entry in ProjectFile(proj.filename + proj.info().ext):
            if not entry.deleted or deleted:
                action(entry)
                if recursive and entry.isproject:
                    subprojs.append(entry)
        for subproj in subprojs:
            lsrec(path + '/' + subproj.name, subproj.phys)

    if not action:
        raise ValueError('action undefined')
    if not project:
        return
    if project[-1] == '/':
        project = project[:-1]
    phys_project = phys(project)
    lsrec(project, phys_project)

def check(project):
    proj = VersionFile(phys(project))
    label_date = proj.last_label().datetime
    def action(entry):
        f = VersionFile(entry.phys)
        v = f.history_until(w=lambda x: x.datetime >= label_date)
        if v:
            print entry.name
    ls(project, True, action=action)

if __name__ == '__main__':
    #ls('$/urmnew/imd')
    #ls('$/urmnew/', recursive=True)
    def a(entry): print entry
    def sa(path): print '\n' + path + ':'
    ls('$/urmnew/', True, action=a, subaction=sa)
    #check('$/urmnew/lib2')

    print phys_cache
